﻿using System;
using System.Collections.Generic;
using Microsoft.Win32;

namespace VSTweaker
{
    public class ExternalTool : IDisposable
    {
        private RegistryKey _key;

        public ExternalTool(RegistryKey key)
        {
            _key = key;
        }

        public string Name
        {
            get
            {
                return _key.GetKeyName();
            }
            set
            {
                var parentKey = _key.GetParentKey();
                parentKey.RenameSubKey(_key.GetKeyName(), value);
            }
        }

        public string Arguments
        {
            get
            {
                return _key.GetValue("ToolArg").ToString();
            }
            set
            {
                _key.SetValue("ToolArg", value);
            }
        }

        public string Command
        {
            get
            {
                return _key.GetValue("ToolCmd").ToString();
            }
            set
            {
                _key.SetValue("ToolCmd", value);
            }
        }

        public string Directory
        {
            get
            {
                return _key.GetValue("ToolDir").ToString();
            }
            set
            {
                _key.SetValue("ToolDir", value);
            }
        }

        public static IEnumerable<ExternalTool> GetAll(string version, string instance)
        {
            var regItems = new List<ExternalTool>();

            var hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);

            using (var vsKey = hklm.OpenSubKey(string.Format("Software\\Wow6432Node\\Microsoft\\VisualStudio\\{0}{1}", version, instance)))
            {
                if (vsKey == null) return null;
                using (var externalToolsKey = vsKey.OpenSubKey("External Tools"))
                {
                    if (externalToolsKey == null) return null; 
                    var subKeyNames = externalToolsKey.GetSubKeyNames();
                    foreach (var subKeyName in subKeyNames)
                    {
                        var subKey = externalToolsKey.OpenSubKey(subKeyName);
                        var externalTools = new ExternalTool(subKey);

                        regItems.Add((externalTools));
                    }
                }
            }

            return regItems;
        }

        public override string ToString()
        {
            return Name;
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            if (_key != null)
            {
                _key.Close();
                _key.Dispose();
            }
        }
    }
}
